package com.yoyoyo666.report.service.impl;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.yoyoyo666.report.common.AnnoLogin;
import com.yoyoyo666.report.common.IDUtils;
import com.yoyoyo666.report.mapper.*;
import com.yoyoyo666.report.model.*;
import com.yoyoyo666.report.service.SendMailService;
import com.yoyoyo666.report.view.EasypoiMoreSheetExcelView;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.InputStreamSource;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class SendMailServiceImpl implements SendMailService {

    private final String host = "smtp.motorsc.com";
    private final String defaultEncoding = "utf-8";

    private DateFormat sdf = new SimpleDateFormat("yyyyMMdd");

    @Autowired
    private ReportUserMapper userMapper;

    @Autowired
    private ReportPlanMapper planMapper;

    @Autowired
    private ReportMailMapper mailMapper;

    @Autowired
    private ReportContentMapper contentMapper;

    @Autowired
    private ReportSendLogMapper sendLogMapper;

    private Map<String,JavaMailSenderImpl> senderMap = new HashMap<String, JavaMailSenderImpl>();


    public boolean sendMail(String userId) throws Exception {
        ReportUser reportUser = userMapper.selectByPrimaryKey(userId);
        if(reportUser == null){
            return false;
        }
        JavaMailSenderImpl javaMailSender = senderMap.get(userId);
        if(!senderMap.containsKey(userId)){
            if(reportUser.getMailName().indexOf("@163")>-1){
                javaMailSender = getJavaMail163Sender(reportUser.getMailName(), reportUser.getMailPwd());
            }else{
                javaMailSender = getJavaMailSender(reportUser.getMailName(), reportUser.getMailPwd());
            }
            //senderMap.put(userId,javaMailSender);
        }

        boolean b = sendMail(javaMailSender, reportUser);

        sendLogMapper.insert(new ReportSendLog(IDUtils.getId(),userId,b+"",""));


        return b;
    }



    private  boolean sendMail(JavaMailSenderImpl javaMailSender,ReportUser reportUser) throws Exception {
        List<ReportMail> reportMails = mailMapper.selectAllByUserId(reportUser.getId());
        if(reportMails==null||reportMails.size()==0){
            return false;
        }
        List<String> to = new ArrayList<String>();
        List<String> cc = new ArrayList<String>();
        for (ReportMail reportMail : reportMails) {
            if("0".equals(reportMail.getType().trim())){
                to.add(reportMail.getMail());
            }else{
                cc.add(reportMail.getMail());
            }
        }
        if(to.size()==0){
            throw new Exception("必须配置发送人，抄送人可以空");
        }

        ArrayList<String> list=new ArrayList<String>();

        String[] tos = new String[to.size()];
        String[] ccs = new String[cc.size()];
        to.toArray(tos);
        cc.toArray(ccs);


        MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
        MimeMessageHelper mMessageHelper;
        Properties prop = new Properties();
        mMessageHelper=new MimeMessageHelper(mMessage,true);
        mMessageHelper.setFrom(reportUser.getMailName());//发件人邮箱
        mMessageHelper.setTo(tos);
        if(cc.size()>0){
            mMessageHelper.setCc(ccs);
        }
        mMessageHelper.setSubject(sdf.format(new Date()) + reportUser.getName() + "日报");//邮件的主题
        mMessageHelper.setText("");//邮件的文本内容，true表示文本以html格式打开
        Workbook workbook = getPlanReportWordbook(reportUser);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        InputStreamSource br =  new ByteArrayResource(out.toByteArray());

        String name = reportUser.getName() +"日报.xls";

        mMessageHelper.addAttachment(name,br);
        javaMailSender.send(mMessage);//发送邮件
        return true;
    }

    private JavaMailSenderImpl getJavaMailSender(String username,String password) {
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setUsername(username);
        javaMailSender.setHost(host);
        javaMailSender.setPassword(password);
        javaMailSender.setDefaultEncoding(defaultEncoding);
        Properties p = new Properties();
        p.put("mail.smtp.auth",true);
        p.put("mail.smtp.timeout",20000);
        javaMailSender.setJavaMailProperties(p);
        return javaMailSender;
    }

    private JavaMailSenderImpl getJavaMail163Sender(String username,String password) {
        int port = 465;
        JavaMailSenderImpl javaMailSender = new JavaMailSenderImpl();
        javaMailSender.setUsername(username);
        javaMailSender.setHost("smtp.163.com");
        javaMailSender.setPassword(password);
        javaMailSender.setDefaultEncoding(defaultEncoding);
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.auth", "true");//开启认证
        properties.setProperty("mail.debug", "true");//启用调试
        properties.setProperty("mail.smtp.timeout", "1000");//设置链接超时
        properties.setProperty("mail.smtp.port", Integer.toString(port));//设置端口
        properties.setProperty("mail.smtp.socketFactory.port", Integer.toString(port));//设置ssl端口
        properties.setProperty("mail.smtp.socketFactory.fallback", "false");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");

        javaMailSender.setJavaMailProperties(properties);
        return javaMailSender;
    }


    public  Workbook getReportWordbook(ReportUser reportUser) {

        List<ReportContent> reportContents = contentMapper.selectAll(reportUser.getId(),null);
        ExportParams exportParams = new ExportParams("技术部"+ reportUser.getName() +"工作计划", "个人工作计划");
        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ReportContent.class, reportContents);
        return  workbook;
    }


    @Override
    public Workbook getPlanReportWordbook(ReportUser reportUser) {
        List<ReportContent> reportContents = contentMapper.selectAll(reportUser.getId(),null);
        ExportParams exportParams = new ExportParams("技术部"+ reportUser.getName() +"工作计划", "个人工作记录");
        List<Map<String,Object>> list = new ArrayList<>();
        Map<String,Object> pr = new HashMap<>();
        pr.put("title",exportParams);
        pr.put("entity",ReportContent.class);
        pr.put("data",reportContents);
        list.add(pr);
        List<ReportPlan> plan = planMapper.selectAll(reportUser.getId(),null);
        for (int i = 0; i < plan.size(); i++) {
            plan.get(i).setNum(i+1);
        }
        ExportParams exportParams1 = new ExportParams("技术部"+ reportUser.getName() +"工作计划", "工作计划");
        Map<String,Object> pr1 = new HashMap<>();
        pr1.put("title",exportParams1);
        pr1.put("entity",ReportPlan.class);
        pr1.put("data",plan);
        list.add(pr1);
        Workbook workbook = ExcelExportUtil.exportExcel(list, ExcelType.HSSF);
        return workbook;
    }
}
